package com.wisdudu.blank.data.source.local;

import android.content.Intent;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.wisdudu.blank.app.App;
import com.wisdudu.blank.app.Constants;
import com.wisdudu.blank.app.RealmVersionUpgradeSetting;
import com.wisdudu.blank.data.Injection;
import com.wisdudu.blank.data.bean.CityInfo;
import com.wisdudu.blank.data.bean.SystemImg;
import com.wisdudu.blank.data.bean.UserInfo;
import com.wisdudu.blank.data.repo.UserDataSource;
import com.wisdudu.blank.data.repo.UserRepo;
import com.wisdudu.blank.support.util.ToastUtil;
import com.wisdudu.blank.ui.login.LoginActivity;
import com.wisdudu.frame.support.util.ComputeUtil;

import java.text.ParseException;
import java.util.List;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;
import rx.Observable;


/**
 * Created by qyf on 2016/8/17.
 */

public class UserLocalDataSource implements UserDataSource {
    private static UserLocalDataSource INSTANCE;
    private RealmConfiguration mConfig;
    private Realm mRealm;


    private UserLocalDataSource() {
    }

    private Realm getRealm() {
//        if (mRealm == null) {
        getRealmConfig();
        mRealm = Realm.getDefaultInstance();
//        }
        return mRealm;
    }

    public static UserLocalDataSource getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new UserLocalDataSource();
        }
        return INSTANCE;
    }

    /**
     * 退出登陆调用，所有需清空缓存在此集中处理
     */
    public void logout() {
        setLoginState(false);
    }

    public boolean isFirstLanuncher() {
        return Hawk.get(Constants.HAWK_IS_FIRST_LANUNCHER, true);
    }

    public void setFirstLanuncher(boolean isLanuncher) {
        Hawk.put(Constants.HAWK_IS_FIRST_LANUNCHER, isLanuncher);
    }

    public boolean isLogin() {
        return Hawk.get(Constants.HAWK_IS_USER_LOGIN, false);
    }

    /**
     * 设置用户登陆状态
     */
    public void setLoginState(boolean isLogin) {
        Hawk.put(Constants.HAWK_IS_USER_LOGIN, isLogin);
    }

    @Override
    public void getUserList() {

    }

    public void savePhoneNum(String phoneNum) {
        Hawk.put(Constants.HAWK_PHONE_NUM, phoneNum);
    }

    public String getPhoneNum() {
        return Hawk.get(Constants.HAWK_PHONE_NUM);
    }

    public void saveUserId(String userId) {
        Hawk.put(Constants.HAWK_USERID, userId);
    }

    public String getUid() {
        return Hawk.get(Constants.HAWK_USERID);
    }

    public void saveUserInfo(UserInfo userInfo) {
        mConfig = null;
        savePhoneNum(userInfo.getUsername());
        saveUserId(userInfo.getUid());
        getRealm().beginTransaction();
        getRealm().copyToRealmOrUpdate(userInfo);
        getRealm().commitTransaction();
        //数据库查询测试，跟DBFlow差不多，记住调用关闭 realm.close()
        UserInfo us = getRealm().where(UserInfo.class).equalTo("uid", getUid()).findFirst();
        Logger.d("%s,%s,%s", us.getUsername(), us.getNickname(), us.toString());
//        getRealm().close();
    }

    public void updateUserInfo(String birthday) {
        getRealm().beginTransaction();
        getRealm().where(UserInfo.class).equalTo("uid", getUid()).findFirst().setBirthday(birthday);
        getRealm().commitTransaction();
        Logger.e("getuserinfo " + getRealm().where(UserInfo.class).equalTo("uid", getUid()).findFirst());
    }


    public UserInfo getUserInfo() {
        String uid = getUid();
        UserInfo userInfo = getRealm().where(UserInfo.class).equalTo("uid", uid).findFirst();
        if (userInfo == null) {
            ToastUtil.INSTANCE.toast("登陆失效，请重新登陆");
            UserRepo mUserRepo = Injection.provideUserRepo();
            mUserRepo.logout();
            Intent intent = new Intent(App.getContext(), LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            App.getContext().startActivity(intent);
        }
        return userInfo;
    }


    public RealmConfiguration getRealmConfig() {
        if (mConfig == null) {
            mConfig = new RealmConfiguration.Builder()
                    .name(getPhoneNum() + ".realm")
                    .schemaVersion(RealmVersionUpgradeSetting.version)
                    .deleteRealmIfMigrationNeeded()//调试过程暂用，无需编写migration文件
//                    .migration(new RealmVersionUpgradeSetting())
                    .build();
            Realm.setDefaultConfiguration(mConfig);
        }
        return mConfig;
    }


    /**
     * 修改用户昵称
     *
     * @param nickname 用户昵称
     */
    public void editNickname(String nickname) {
        getRealm().beginTransaction();
        UserInfo userInfo = getRealm().where(UserInfo.class).equalTo("uid", getUid()).findFirst();
        userInfo.setNickname(nickname);
        getRealm().commitTransaction();
    }

    /**
     * 修改用户生日
     *
     * @param birthday 生日
     */
    public void editBirthday(String birthday) {
        getRealm().beginTransaction();
        UserInfo userInfo = getRealm().where(UserInfo.class).equalTo("uid", getUid()).findFirst();
        //根据birthday计算年龄
        try {
            userInfo.setAge(ComputeUtil.getAgeByBirthday(birthday));
        } catch (ParseException e) {
            Logger.d("计算年龄出错，%s", e.toString());
        }
        userInfo.setBirthday(birthday);
        getRealm().commitTransaction();
    }

    /**
     * 修改性别
     *
     * @param sex 性别 1：男 2：女
     */
    public void editSex(Integer sex) {
        getRealm().beginTransaction();
        UserInfo userInfo = getRealm().where(UserInfo.class).equalTo("uid", getUid()).findFirst();
        userInfo.setSex(sex);
        getRealm().commitTransaction();
    }

    public void editVoice(String voice) {
        getRealm().beginTransaction();
        UserInfo userInfo = getRealm().where(UserInfo.class).equalTo("uid", getUid()).findFirst();
        userInfo.setVoiceprint(voice);
        getRealm().commitTransaction();
    }

    public void editAvatar(String avatarurl) {
        getRealm().beginTransaction();
        UserInfo userInfo = getRealm().where(UserInfo.class).equalTo("uid", getUid()).findFirst();
        userInfo.setFaces(avatarurl);
        getRealm().commitTransaction();
    }

    public void saveCityInfo(List<CityInfo> cityInfos) {
        getRealm().beginTransaction();
        getRealm().copyToRealmOrUpdate(cityInfos);
        getRealm().commitTransaction();
    }

    public Observable<List<CityInfo>> getCityInfo(int provinceid) {
        RealmResults<CityInfo> cityInfos = getRealm().where(CityInfo.class).equalTo("provinceid", provinceid).findAll();
        return Observable.just(getRealm().copyFromRealm(cityInfos));
    }

    public void closeRealm() {
        if (mRealm != null) {
            mRealm.close();
        }
    }

    public void updateSysPhotoList(List<SystemImg> systemImgs) {
        for (SystemImg systemImg : systemImgs) {
            getRealm().beginTransaction();
            getRealm().copyToRealmOrUpdate(systemImg.photoEntities);
            getRealm().commitTransaction();
        }
        getRealm().beginTransaction();
        getRealm().copyToRealmOrUpdate(systemImgs);
        getRealm().commitTransaction();
    }

    public Observable<List<SystemImg>> getSysPhotoList() {
        RealmResults<SystemImg> systemImgs = getRealm().where(SystemImg.class).findAll();
        return Observable.just(getRealm().copyFromRealm(systemImgs));
    }

    public void updateHouseInfo(int houseId, String houseName) {
        getRealm().beginTransaction();
        UserInfo userInfo = getRealm().where(UserInfo.class).equalTo("uid", getUid()).findFirst();
        userInfo.setHouseid(houseId + "");
        userInfo.setHousename(houseName);
        getRealm().commitTransaction();
    }

}
